/**
 * HTTP请求工具函数
 */

interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  headers?: Record<string, string>
  body?: any
}

interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

const baseURL = import.meta.env.VITE_API_BASE_URL || ''

export const request = async <T = any>(
  url: string,
  options: RequestOptions = {}
): Promise<ApiResponse<T>> => {
  const { method = 'GET', headers = {}, body } = options

  const config: RequestInit = {
    method,
    headers: {
      'Content-Type': 'application/json',
      ...headers
    }
  }

  if (body && method !== 'GET') {
    config.body = JSON.stringify(body)
  }

  try {
    const response = await fetch(`${baseURL}${url}`, config)
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.message || 'Request failed')
    }
    
    return result
  } catch (error) {
    console.error('Request error:', error)
    throw error
  }
}

export const get = <T = any>(url: string, headers?: Record<string, string>) => 
  request<T>(url, { method: 'GET', headers })

export const post = <T = any>(url: string, body?: any, headers?: Record<string, string>) => 
  request<T>(url, { method: 'POST', body, headers })

export const put = <T = any>(url: string, body?: any, headers?: Record<string, string>) => 
  request<T>(url, { method: 'PUT', body, headers })

export const del = <T = any>(url: string, headers?: Record<string, string>) => 
  request<T>(url, { method: 'DELETE', headers })